package com.woke.photoactivity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zhongcai.online.R;
import com.woke.photoactivity.ListImageDirPopupWindow.OnImageDirSelected;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

public class PhotocheckActivity extends Activity implements OnImageDirSelected {

	private GridView mGridView;
	private ProgressDialog mProgressDialog;
	/**
	 * ��ʱ�ĸ����࣬���ڷ�ֹͬһ���ļ��еĶ��ɨ��
	 */
	private HashSet<String> mDirPaths = new HashSet<String>();
	/**
	 * ɨ���õ����е�ͼƬ�ļ���
	 */
	private List<ImageFloder> mImageFloders = new ArrayList<ImageFloder>();
	int totalCount = 0;
	/**
	 * �洢�ļ����е�ͼƬ����
	 */
	private int mPicsSize;
	/**
	 * ͼƬ���������ļ���
	 */
	private File mImgDir;
	/**
	 * ���е�ͼƬ
	 */
	private List<String> mImgs;
	private MyAdapter mAdapter;
	private RelativeLayout mBottomLy;
	private ListImageDirPopupWindow mListImageDirPopupWindow;
	private Handler mHandler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			mProgressDialog.dismiss();
			// ΪView�����
			data2View();
			// ��ʼ��չʾ�ļ��е�popupWindw
			initListDirPopupWindw();
		}
	};
	private TextView mTextView,mImageCount;
	private int mScreenHeight;
	private int parent = 0;
	
	/**
	 * ΪView�����
	 */
	private void data2View(){
		if (mImgDir == null){
			Toast.makeText(getApplicationContext(), "一张图片没扫描到",
					Toast.LENGTH_SHORT).show();
			return;
		}

		mImgs = Arrays.asList(mImgDir.list());
		/**
		 * ���Կ����ļ��е�·����ͼƬ��·���ֿ����棬����ļ������ڴ����ģ�
		 */
		mAdapter = new MyAdapter(getApplicationContext(), mImgs,
				R.layout.grid_item, mImgDir.getAbsolutePath(),mTextView,parent);
		mGridView.setAdapter(mAdapter);
		mImageCount.setText(totalCount + "张");
	};
	
	/**
	 * ��ʼ��չʾ�ļ��е�popupWindw
	 */
	private void initListDirPopupWindw(){
		mListImageDirPopupWindow = new ListImageDirPopupWindow(
				LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.7),
				mImageFloders, LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.list_dir, null));

		mListImageDirPopupWindow.setOnDismissListener(new OnDismissListener(){

			@Override
			public void onDismiss(){
				// ���ñ�����ɫ�䰵
				WindowManager.LayoutParams lp = getWindow().getAttributes();
				lp.alpha = 1.0f;
				getWindow().setAttributes(lp);
			}
		});
		// ����ѡ���ļ��еĻص�
		mListImageDirPopupWindow.setOnImageDirSelected(this);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photocheck);
		
		Intent intent = getIntent();
		parent = intent.getIntExtra("parent", 0);
		DisplayMetrics outMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
		mScreenHeight = outMetrics.heightPixels;
		intview();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mProgressDialog.dismiss();
	}

	private void intview() {
		mTextView = (TextView) findViewById(R.id.text_checkedphoto_no);
		mGridView = (GridView) findViewById(R.id.gridView_photo);
		mImageCount = (TextView) findViewById(R.id.id_total_count);
		mBottomLy = (RelativeLayout) findViewById(R.id.id_bottom_ly);
		findViewById(R.id.image_back_photocheck).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		mTextView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
//				ArrayList<String> photolist = mAdapter.photolist();
				String photoresult = mAdapter.photoresult;
				Log.e("parent"+parent, "****"+photoresult);
//				if(photoresult != null){
					if(parent < 4){
						Intent intent = new Intent();
						intent.setAction("com.woke.borrwforwhy");
//						intent.setClass(PhotocheckActivity.this, RealnameActivity.class);
						intent.putExtra("feyanUsersIdr", photoresult);
						intent.putExtra("parent", parent);
						sendBroadcast(intent);
//						setResult(220, intent);
						Log.e("parent"+parent+" "+photoresult, ""+parent);
						finish();
					} 
					else if(parent == 10){
						Intent intent = new Intent();
						intent.setAction("com.woke.realnameavitivyt");
//						intent.setClass(PhotocheckActivity.this, RealnameActivity.class);
						intent.putExtra("feyanUsersIdr", photoresult);
						intent.putExtra("parent", parent);
						sendBroadcast(intent);
//						setResult(219, intent);
						Log.e("parent"+parent+" "+photoresult, ""+parent);
						finish();
					}else if(parent == 20){
						Intent intent = new Intent();
						intent.setAction("com.woke.whyalwaysfalse");
//						intent.setClass(PhotocheckActivity.this, RealnameActivity.class);
						intent.putExtra("feyanUsersIdr", photoresult);
						intent.putExtra("parent", parent);
						sendBroadcast(intent);
//						setResult(219, intent);
						Log.e("parent"+photoresult, ""+parent);
						finish();
					}
//					else if(parent == 4){
//						Intent intent = new Intent();
//						intent.setAction("com.woke.borrowforactivity");
////						intent.setClass(PhotocheckActivity.this, RealnameActivity.class);
//						intent.putExtra("feyanUsersIdr", parent);
//						intent.putExtra("parent", parent);
////						setResult(219, intent);
//						Log.e("parent"+photoresult, ""+parent);
//						finish();
//					}
//					else{
//						Intent intent = new Intent();
//						intent.setAction("com.zhitu.broadcastreceivrephoto");
//						intent.putExtra("feyanUsersId", photoresult);
//						sendBroadcast(intent);
//						finish();
//					}
//				}
			}
		});
		getImages();
		initEvent();
	}
	
	public void adaptermethod(){
		
	}
	
	private void initEvent(){
		/**
		 * Ϊ�ײ��Ĳ������õ���¼�������popupWindow
		 */
		mBottomLy.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v){
				mListImageDirPopupWindow
						.setAnimationStyle(R.style.anim_popup_dir);
				mListImageDirPopupWindow.showAsDropDown(mBottomLy, 0, 0);

				// ���ñ�����ɫ�䰵
				WindowManager.LayoutParams lp = getWindow().getAttributes();
				lp.alpha = .3f;
				getWindow().setAttributes(lp);
			}
		});
	}
	
	/**
	 * ����ContentProviderɨ���ֻ��е�ͼƬ���˷��������������߳��� ���ͼƬ��ɨ�裬���ջ��jpg�����Ǹ��ļ���
	 */
	private void getImages(){
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)){
			Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
			return;
		}
		// ��ʾ�����
		mProgressDialog = ProgressDialog.show(PhotocheckActivity.this, null, "正在加载...");

		new Thread(new Runnable(){
			@Override
			public void run(){

				String firstImage = null;

				Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				ContentResolver mContentResolver = PhotocheckActivity.this
						.getContentResolver();

				// ֻ��ѯjpeg��png��ͼƬ
				Cursor mCursor = mContentResolver.query(mImageUri, null,
						MediaStore.Images.Media.MIME_TYPE + "=? or "
								+ MediaStore.Images.Media.MIME_TYPE + "=?",
						new String[] { "image/jpeg", "image/png" },
						MediaStore.Images.Media.DATE_MODIFIED);

//				Log.e("TAG", mCursor.getCount() + "");
				while (mCursor.moveToNext()){
					// ��ȡͼƬ��·��
					String path = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Images.Media.DATA));

//					Log.e("TAG", path);
					// �õ���һ��ͼƬ��·��
					if (firstImage == null)
						firstImage = path;
					// ��ȡ��ͼƬ�ĸ�·����
					File parentFile = new File(path).getParentFile();
					if (parentFile == null)
						continue;
					String dirPath = parentFile.getAbsolutePath();
					ImageFloder imageFloder = null;
					// ����һ��HashSet��ֹ���ɨ��ͬһ���ļ��У���������жϣ�ͼƬ�����������൱�ֲ���~~��
					if (mDirPaths.contains(dirPath)){
						continue;
					} else{
						mDirPaths.add(dirPath);
						// ��ʼ��imageFloder
						imageFloder = new ImageFloder();
						imageFloder.setDir(dirPath);
						imageFloder.setFirstImagePath(path);
					}

					int picSize = parentFile.list(new FilenameFilter(){
						@Override
						public boolean accept(File dir, String filename){
							if (filename.endsWith(".jpg")
									|| filename.endsWith(".png")
									|| filename.endsWith(".jpeg"))
								return true;
							return false;
						}
					}).length;
					totalCount += picSize;

					imageFloder.setCount(picSize);
					mImageFloders.add(imageFloder);

					if (picSize > mPicsSize){
						mPicsSize = picSize;
						mImgDir = parentFile;
					}
				}
				mCursor.close();

				// ɨ����ɣ������HashSetҲ�Ϳ����ͷ��ڴ���
				mDirPaths = null;

				// ֪ͨHandlerɨ��ͼƬ���
				mHandler.sendEmptyMessage(0x110);

			}
		}).start();

	}

	@Override
	public void selected(ImageFloder floder) {
		mImgDir = new File(floder.getDir());
		mImgs = Arrays.asList(mImgDir.list(new FilenameFilter(){
			@Override
			public boolean accept(File dir, String filename){
				if (filename.endsWith(".jpg") || filename.endsWith(".png")
						|| filename.endsWith(".jpeg"))
					return true;
				return false;
			}
		}));
		/**
		 * ���Կ����ļ��е�·����ͼƬ��·���ֿ����棬����ļ������ڴ����ģ�
		 */
		mAdapter = new MyAdapter(getApplicationContext(), mImgs,
				R.layout.grid_item, mImgDir.getAbsolutePath(),mTextView,parent);
		mGridView.setAdapter(mAdapter);
		// mAdapter.notifyDataSetChanged();
//		mImageCount.setText(floder.getCount() + "��");
//		mChooseDir.setText(floder.getName());
		mListImageDirPopupWindow.dismiss();
	}
	
}
